class Game < ActiveRecord::Base
	belongs_to :fset
	belongs_to :user


#
# This doesn't have an important return value. We just save 
# the result to both the game score and the 
# card in card_stats
#
  def score_card (flashcard_id, correct)
	if correct
		self.score = self.score + 1
	else
		self.wrong_count = self.wrong_count + 1
	end
	card_score_entity = CardScore.get_card(self.user, self.fset, flashcard_id)
	card_score_entity.update_card( correct )
	save
  end

	
#
# This returns a shuffled array of the id for
# each card in the set.
#
  def get_cards(game_mode, current_user)
    if game_mode == 1 # just wrong ones
		scores = Flashcard.find(:all, :joins => :card_scores, :select => "flashcards.id, flashcards.question, flashcards.answer", :conditions => ["card_scores.user_id = ? and card_scores.fset_id = ? and last_three = ?", current_user, fset_id, 0])	
		scores.sort!{rand <=> 0.5}
		scores.collect{ |card| card.id }
	else
		cards = Flashcard.find(:all, :conditions => ["fset_id = ?", fset_id])
		cards.sort!{rand <=> 0.5}
		cards.collect{ |card| card.id }
	end
	# missed_last_time?
  end
  
  def self.prepare_graph (applicable_cardstats)
	x = applicable_cardstats.collect{ |one_game|  Array[one_game.created_at.year.to_s + "-" + one_game.created_at.month.to_s + "-" + one_game.created_at.day.to_s , one_game.percent_correct] }
	x
  end
  
  def percent_correct
	total_times = self.score + self.wrong_count
	if total_times == 0
		100
	else
		percentage = 100 * self.score / total_times
	end
end
    
  
  #
  # This returns true if the game is over and false if it
  # is not over. This is called from the games controller to 
  # see if it should redirect to the "done" view
  #
  # TODO: Right now this is never being called.
  # TODO: The "done" view doesn't exist
  def self.game_over?(shuffled_cards)
	shuffled_cards.length == 0
  end

end